﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using monitor_2_DBwork;

namespace monitor_server_2_WPF.DeviceListParamPanels
{
    /// <summary>
    /// Логика взаимодействия для StationParamPanel.xaml
    /// </summary>
    public partial class StationParamPanel
    {
        private readonly List<string> _blrs;
        private DeviceTreeItem.StationInfo _curInfo;
        private DeviceTreeItem.StationInfo _startInfo;
        private static readonly DeviceListTabControl.UpdateRegionTreeNodeDelegate UpdateRegionTreeNode = DeviceListTabControl.UpdateRegion;

        private StationParamPanel()
        {
            InitializeComponent();
            CoordinatesLabel.Content = Res.Rm.GetString("Coordinates");
            BlrLabel.Content = Res.Rm.GetString("BLR");
            AcceptButton.Content = new MyDockPanel(Res.GetBitMapFromPng("accept_image_16"), Res.Rm.GetString("Accept"));
            DeleteButton.Content = new MyDockPanel(Res.GetBitMapFromPng("delete_image_16"), Res.Rm.GetString("Delete"));
            AddDeviceExpander.Header = Res.Rm.GetString("AddDevice");
            _blrs = DBwork.GetBlrList();
            BlrBox.ItemsSource = _blrs;
            CoordinatesA.AddAvailableDestination(CoordinateSetter.Destinations.East);
            CoordinatesA.DegreeBox.MaximumValue = 32;
            CoordinatesA.DegreeBox.MinimumValue = 23;
            CoordinatesA.DataChangedEvent += CoordinatesOnDataChangedEvent;
            CoordinatesB.AddAvailableDestination(CoordinateSetter.Destinations.North);
            CoordinatesB.DegreeBox.MaximumValue = 56;
            CoordinatesB.DegreeBox.MinimumValue = 51;
            CoordinatesB.DataChangedEvent += CoordinatesOnDataChangedEvent;
            BlrBox.SelectionChanged += BlrBoxOnSelectionChanged;
            
        }

        private static StationParamPanel _panel;

        public static UIElement GetPanel(DeviceTreeItem.StationInfo info)
        {
            if(_panel == null)
                _panel = new StationParamPanel();
            _panel.ToOriginal();
            _panel._curInfo = info.GetInfo;
            _panel._startInfo = info.GetInfo;
            if (_panel._startInfo.Coordinates == string.Empty)
                _panel._startInfo.Coordinates = "000000000000";
            _panel.StationBox.Text = info.Station;
            _panel.BlrBox.SelectedItem = info.BLR;
            _panel.SetCoordinates(_panel._startInfo.Coordinates);
            _panel.AcceptButton.IsEnabled = false;

            return _panel;
        }

        private void ToOriginal()
        {
            AddDevicePanelGrid.Children.Clear();
            AddDevicePanelGrid.Visibility = Visibility.Collapsed;
            AddDeviceExpander.Visibility = Visibility.Visible;
            AddDeviceExpander.IsExpanded = false;
        }

        private void AcceptButton_Click(object sender, RoutedEventArgs e)
        {
            var parameters = new[]{_startInfo.Station, _curInfo.Station, _curInfo.BLR, _curInfo.Coordinates};
            if (!DBwork.UpdateData("station", parameters))
            {
                MessageBox.Show("Record can not be updated.", Res.Rm.GetString("Error"), MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            UpdateRegionTreeNode();
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            var res = MessageBox.Show(Res.Rm.GetString("DeleteElementDialog") + "?\r\n" + StationBox.Text.Trim(), Res.Rm.GetString("Warning"), MessageBoxButton.YesNo,
                MessageBoxImage.Question);
            if (res != MessageBoxResult.Yes)
                return;
            if(!DBwork.DeleteData("station", StationBox.Text.Trim()))
            {
                MessageBox.Show("Record can not be deleted.", Res.Rm.GetString("Error"), MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            UpdateRegionTreeNode();
        }

        private void SetCoordinates(string coords)
        {
            var hlen = coords.Length/2;
            CoordinatesA.Value = coords.Remove(hlen);
            CoordinatesB.Value = coords.Remove(0, hlen);
        }

        private void DataChanged()
        {
            AcceptButton.IsEnabled = !_curInfo.Equals(_startInfo);
        }

        private void BlrBoxOnSelectionChanged(object sender, SelectionChangedEventArgs selectionChangedEventArgs)
        {
            var box = sender as ComboBox;
            _curInfo.BLR = box.SelectedItem.ToString();
            DataChanged();
        }

        private void CoordinatesOnDataChangedEvent(string coords)
        {
            var stra = CoordinatesA.Value.Substring(1, 6);
            var strb = CoordinatesB.Value.Substring(1, 6);
            _curInfo.Coordinates = stra + strb;
            DataChanged();
        }

        private void StationBox_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            if (DeleteButton == null)
                return;
            string station = ((TextBox) sender).Text;
            _curInfo.Station = station;
            DataChanged();
            var chk = DBwork.CheckStationExistance(station);
            if (chk.StartsWith("err:"))
            {
                MessageBox.Show(chk.Remove(0, 4));
                return;
            }
            DeleteButton.IsEnabled = chk.Equals("1");
        }

        private void AddDeviceExpander_OnExpanded(object sender, RoutedEventArgs e)
        {
            AddDevicePanelGrid.Visibility = Visibility.Visible;
            var exp = sender as Expander;
            exp.Visibility = Visibility.Collapsed;
            AddDevicePanelGrid.Children.Add(AddDevicePanel.GetPanel(_startInfo.Station));
        }
    }
}
